package com.itheima.exception;


import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.ServletException;
import java.nio.file.AccessDeniedException;

@RestControllerAdvice
@Slf4j
public class MyHandlerException {

	/**
	 * 处理运行时异常
	 * @return
	 */
	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(RuntimeException.class)
	public Result handlerRuntimeException(Exception e){


		log.debug("运行时异常:"+e);
		if(e instanceof AccessDeniedException){

			return new Result(false, "未登陆或者权限不足!!!");
		}

		return new Result(false, MessageConst.ACTION_FAIL);

	}
	@ExceptionHandler({
			ServletException.class,                     // mediaType不匹配、method不匹配……
			HttpMessageConversionException.class,       //http body转换异常，@RequestBody的参数
			MethodArgumentNotValidException.class ,     //http请求缺少查询参数
			MethodArgumentTypeMismatchException.class   //http请求参数类型不匹配
	})
	public Result handlerOtherException(Exception e) throws Exception {
		System.out.println("出错了");
		throw e;
	}

	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler({
			Exception.class
	})
	public Result handlerException(Exception e) {
		log.debug("error：" +e );
		return new Result(false, MessageConst.ACTION_FAIL);
	}

}
